package com.ruoyi.common.utils;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * XML转换工具
 *
 * @author by jianan.liu on 16/9/23.
 */
public class JaxbXmlUtil {
    private static final Logger logger = LoggerFactory.getLogger(JaxbXmlUtil.class);
    private static Map<String, String> escapeMap;

    static {
        HashMap<String, String> tmpMap = Maps.newHashMap();
        tmpMap.put("&lt;", "<");
        tmpMap.put("&gt;", ">");
        tmpMap.put("&amp;", "&");
        tmpMap.put("&apos;", "’");
        tmpMap.put("&quot;", "");
        escapeMap = ImmutableMap.copyOf(tmpMap);
    }




    /**
     * JavaBean转换成xml 默认编码UTF-8
     *
     * @param obj
     * @return
     */
    public static String convertToXml(Object obj) {
        return convertToXml(obj, "UTF-8");
    }

    /**
     * JavaBean转换成xml,支持CData
     *
     * @param obj
     * @param encoding
     * @return
     */
    public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            logger.error("covert to xml error, obj: {}", obj, e);
        }

        return result;
    }

    /**
     * xml转换成JavaBean
     *
     * @param xml
     * @param c
     * @return
     */
    @SuppressWarnings ("unchecked")
    public static <T> T converyToJavaBean(String xml, Class<T> c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            logger.error("covert to bean error, xml: {}", xml, e);
        }
        return t;
    }

    /**
     *
     * @param obj
     * @return
     */
  public static String convertXmlWithCDATA(Object obj){
      String xml = convertToXml(obj);
      for (String key : escapeMap.keySet()) {
          xml = xml.replace(key , escapeMap.get(key));
      }
      return xml;
  }
}
